package com.alili_tv.system.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectionException;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义元数据对象处理器
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    private MetaObject metaObject;
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充【insert】...");
        log.info(metaObject.toString());
        this.metaObject = metaObject;

        ignoreException("createTime", LocalDateTime.now());
        ignoreException("updateTime", LocalDateTime.now());
        ignoreException("createUser", BaseContext.getCurrentId());
        ignoreException("updateUser", BaseContext.getCurrentId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充【update】...");
        log.info(metaObject.toString());
        this.metaObject = metaObject;

        ignoreException("updateTime", LocalDateTime.now());
        ignoreException("updateUser", BaseContext.getCurrentId());
    }

    /**
     * 当类中不存在以上其中的字段时，自动生成会报异常：ReflectionException
     * @param property
     * @param value
     */
    private void ignoreException(String property, Object value) {
        try {
            metaObject.setValue(property, value);
        } catch (ReflectionException ignored) {
        }
    }
}
